﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;

namespace Common.Framework.Core.Foundation
{
    public static class AssemblyFoundation
    {
        /// <summary>
        /// 获得所有项目的程序集
        /// </summary>
        /// <returns></returns>
        public static Assembly[] GetAllProjectAssemblies()
        {
            //自动到项目根目录中查找 名称带Main的dll和名称带Module的dll

            //Common.Framework.Core.dll
            //var assemblyName = Assembly.GetExecutingAssembly().GetName().Name

            string dllPath = ConfigurationPath.Combine(AppDomain.CurrentDomain.BaseDirectory);

            //Common.Framework.Main.Api.dll
            IEnumerable<Assembly> mainAssemblyList = Directory.EnumerateFiles(dllPath, "*.Main.Api.dll").Select(AssemblyLoadContext.Default.LoadFromAssemblyPath);
            //Common.Framework.Module *.Api.dll
            IEnumerable<Assembly> moduleAssemblyList = Directory.EnumerateFiles(dllPath, "*.Module*.Api.dll").Select(AssemblyLoadContext.Default.LoadFromAssemblyPath);
            //Common.Framework.Module *.dll
            IEnumerable<Assembly> consoleModuleAssemblyList = Directory.EnumerateFiles(dllPath, "*.Module*.dll").Select(AssemblyLoadContext.Default.LoadFromAssemblyPath);
           // IEnumerable<Assembly> consoleModuleAssemblyList = Directory.EnumerateFiles(dllPath, "VehicleApi*.dll").Select(AssemblyLoadContext.Default.LoadFromAssemblyPath);

            return mainAssemblyList.Concat(moduleAssemblyList.ToArray()).Concat(consoleModuleAssemblyList.ToArray()).Distinct().ToArray();
        }
    }
}
